package com.masterclient.app.modules.pickgoods;

import android.graphics.Color;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.toast.ToastUtil;

import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.pickgoods.adapter.PickGoodsListAdapter;
import com.masterclient.app.modules.pickgoods.beans.PickGoodsBean;
import com.masterclient.app.modules.pickgoods.contract.PickGoodsListContract;
import com.masterclient.app.modules.pickgoods.contract.PickGoodsListPresenter;
import com.eoner.uikit.header.MyRefreshHead;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

@Route(path = AroutePath.PICK_GOODS_LIST_FRAGMENT)
public class PickGoodsListFragment extends BaseFragment<PickGoodsListPresenter> implements PickGoodsListContract.View {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.view_tip)
    View viewTip;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.view_root)
    LinearLayout viewRoot;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.scroll_layout)
    NestedScrollView scrollLayout;

    private View emptyView;
    private PickGoodsListAdapter pickGoodsListAdapter;
    private List<PickGoodsBean.ItemBean> list = new ArrayList<>();
    private SelectPickGoodsListener listener;
    private String buyProduct = "";
    private boolean hasZeroNum = false;
    private RxBus rxBus;

    public static PickGoodsListFragment newInstance() {
        return new PickGoodsListFragment();
    }

    public void setSelectPickGoodsListener(SelectPickGoodsListener listener) {
        this.listener = listener;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        setFullScreenAndTransparent(getActivity());
        return inflater.inflate(R.layout.fragment_pick_goods_list, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();
        ARouter.getInstance().inject(this);
        rxBus = RxBus.$();

        refreshLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
        refreshLayout.setOnRefreshListener(refreshLayout -> mPresenter.getPickGoodsListInfo());
        emptyView = View.inflate(getActivity(), R.layout.empty_pick_goods, null);
        (emptyView.findViewById(R.id.tv_to_purchase)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build(AroutePath.PURCHASE_ACTIVITY).navigation();
            }
        });
        pickGoodsListAdapter = new PickGoodsListAdapter(getActivity(), viewRoot, list, (isCheck, productId, num) -> {
            for (int i = 0; i < list.size(); i++) {
                if (productId.equals(list.get(i).productId)) {
                    list.get(i).isChecked = isCheck;
                    if (recyclerView.isComputingLayout()) {
                        int finalI = i;
                        recyclerView.postDelayed(() -> pickGoodsListAdapter.notifyItemChanged(finalI), 100);
                    }
                }
            }
            buyProduct = getBuyProduct(list);
            listener.onCheckItem(list == null || list.size()<1,buyProduct, hasZeroNum);
        });
        pickGoodsListAdapter.setEmptyView(emptyView);
        emptyView.setVisibility(View.GONE);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(null);
        pickGoodsListAdapter.bindToRecyclerView(recyclerView);

        mPresenter.getPickGoodsListInfo();

        rxBus.OnEvent(rxBus.register(Config.SUBMIT_PICK_GOODS_ORDER),new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                mPresenter.getPickGoodsListInfo();
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (rxBus != null) {
            rxBus.unregister(Config.SUBMIT_PICK_GOODS_ORDER);
        }
    }

    /**
     * 获取勾选商品id & 数量
     */
    private String getBuyProduct(List<PickGoodsBean.ItemBean> list) {
        JSONObject buyProductsInfo = new JSONObject();
        hasZeroNum = false;
        try {
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).isChecked) {
                        if (TextUtils.isEmpty(list.get(i).num) || Integer.parseInt(list.get(i).num) == 0) {
                            hasZeroNum = true;
                        }
                        buyProductsInfo.put(list.get(i).productId,
                                list.get(i).num);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (buyProductsInfo.toString().equals("{}")) {
            return "";
        } else {
            return buyProductsInfo.toString();
        }
    }

    @Override
    public void showPickGoodsListInfo(PickGoodsBean bean) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh(true);
        }
        list.clear();
        buyProduct = "";
        listener.onCheckItem(!(bean != null && bean.items != null && bean.items.size() > 0),"", hasZeroNum);
        if (bean != null && bean.items != null && bean.items.size() > 0) {
            emptyView.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(bean.topTips)) {
                tvTip.setText(bean.topTips);
                viewTip.setVisibility(View.VISIBLE);
            } else {
                viewTip.setVisibility(View.GONE);
            }
            list.addAll(bean.items);
            pickGoodsListAdapter.setNewData(bean.items);
        } else {
            pickGoodsListAdapter.setNewData(null);
            emptyView.setVisibility(View.VISIBLE);
            viewTip.setVisibility(View.GONE);
            scrollLayout.setBackgroundColor(Color.parseColor("#ffffff"));
        }
    }

    @Override
    public void showFail(String msg) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh(false);
        }
        emptyView.setVisibility(View.GONE);
        ToastUtil.showToast(msg);
    }

    public interface SelectPickGoodsListener {
        void onCheckItem(boolean showEmpty, String buyProduct, boolean hasZeroNum);
    }
}
